
function httprequest(url,data){
    return new Promise((resolve, reject) => {
        global.request({
            url: url,
            method: "POST",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: data
        }, function(error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            }else {
                reject(error);
            }
        });
    })
};



class WxAppPlugin {
    constructor({
                    //小程序的appid
                    appid="wxb82ed6f75c3a22ad",
                    //公众平台申请的公众号appsecret
                    appsecret="999915ad9371781036b2bf8f917a28fd",
                }) {
        this.appid=appid;
        this.appsecret=appsecret;
    }

    async getAccessToken(){
        if(global.accessTokenCache  && (Date.now()+100000) < global.accessTokenCache.expires_time){
            return global.accessTokenCache;
        }
        const appid = this.appid;
        const secret = this.appsecret;
        const infoUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + secret;
        let r= await  M.request.get(infoUrl);
        global.accessTokenCache=r;
       return r;
    }


    async urlschemeGenerate(){
        let token=await this.getAccessToken();
        let access_token=token.access_token;
        let r=await  httprequest("https://api.weixin.qq.com/wxa/generatescheme?access_token="+access_token);
        return r;
    }

    install(app,args){

    }
}

module.exports = WxAppPlugin;

